clear all
close all
clc

% read-in mesh using given mesh reader
MeshData = ReadGmsh('mesh.msh');

%%%% Plot the mesh using patch command:

% setup data in the way the patch command expects it.  It requires
% information about the triangles in the mesh so we give it the x and y
% coordinates of the nodes of each triangle.  The physics number of the
% triangle is stored in Zp
Xp = zeros(MeshData.nElements2D, 3);
Yp = zeros(MeshData.nElements2D, 3);
Zp = zeros(MeshData.nElements2D, 3);

for ii = 1:1:length(Xp)
    Xp(ii,:) = MeshData.xNodes(MeshData.EleMatrix2D(ii,:));
    Yp(ii,:) = MeshData.yNodes(MeshData.EleMatrix2D(ii,:));
    Zp(ii,:) = MeshData.PhysNumber2D(MeshData.EleMatrix2D(ii,:));
end %for

% create a figure to plot into
figure('Name','Patch plot of Gmsh mesh'); 

% Create the patch plot and store it in p.  Then define plotting parameters. 
p = patch(transpose(Xp),transpose(Yp),'b');
set(p,'FaceColor','flat', 'CData',MeshData.PhysNumber2D ,'CDataMapping','scaled')



%%%% Plot the mesh using imagesc command:

% to use imagesc, the unstructured mesh must be converted to a regular
% grid.  This is done by setting up the grid in a matrix and then
% interpolating the physics numbers to the grid points.

% set the number of points in the x and y directions of the new grid.  
numpts = 1000;

% get the coordinates of the centroids of the mesh triangles.
x = MeshData.centroids(:,1);
y = MeshData.centroids(:,2);

% create evenly spaced grid with values between -3 and 3 (in both x and y
% directions).  This grid will have dimensions numpts by numpts.  The grid
% point coordinates are stored in Xr and Yr.
bmin = -3;
bmax = 3;
xr = linspace(bmin,bmax,numpts);
yr = linspace(bmin,bmax,numpts);
[Xr,Yr] = meshgrid(xr,yr);

% interpolate the data from the unstructured mesh element centroids to the 
% regular grid points.
interpData = griddata(x,y,MeshData.PhysNumber2D,Xr,Yr,'nearest');

%  Create figure and plot the data
figure('Name','Imagesc plot of Gmsh mesh'); 
imagesc(interpData);

